import { objectAny } from "../options/base";
import { assertTokenIsValid } from "./doCloud";
import { showModal } from "./utils";

const uniIdCo = uniCloud.importObject('uni-id-co', { customUI: true })


export async function uniCheckUserIsLogin(
	force : boolean | undefined = false,
	inviteCode : string | undefined = ''
) : Promise<{
	status : 0 | 1 | 2 | 3;
	msg : string
}> {
	return new Promise(async resolve => {
		let token = uni.getStorageSync('uni_id_token');
		if (force) {
			token = false;
		}
		if (!token) {
			uni.login({
				provider: 'weixin',
				success: async ({ errMsg, code }) => {
					if (errMsg && errMsg.trim() === `login:ok`) {
						try {
							const result = await uniIdCo.loginByWeixin({
								code,
								inviteCode
							})
							const { uid, type } = result;
							console.log(result);
							return resolve({
								status: 0,
								msg: ``
							})
						} catch (error) {
							console.error(error)
							showModal({
								title: `异常提示`,
								showCancel: false,
								content: `登录失败请稍后再试`
							});
							return resolve({
								status: 1,
								msg: `使用微信一键登录，访问服务器失败`
							})
						}
					} else {
						console.log(errMsg)
						return resolve({
							status: 2,
							msg: `使用微信一键登录状态异常`
						})
					}
				},
				fail: async (error : objectAny) => {
					console.error(error)
					showModal({
						title: `提示`,
						showCancel: false,
						content: `登录失败请联系客服`
					});
					return resolve({
						status: 3,
						msg: `使用微信一键登录失败，可能该平台不支持`
					})
				}
			});
		} else {
			console.log(`======> 当前本地token已经存在，检查token是否过期 <======`)
			const tokenIsValid = await assertTokenIsValid();
			if (!tokenIsValid) {
				console.log(`xxxxxx=> token异常 需要重新获取新的token <=xxxxxx`)
				return resolve(uniCheckUserIsLogin(true))
			}
			return resolve({
				status: 0,
				msg: ``
			})
		}
	})
}